const fs = require('fs');
const path = require('path');
const {exec, execFile} = require("child_process");

//获取当前时间
const getCurrentTime = (emptyStr = false) => {
    let time = new Date();
    let year = time.getFullYear()
    let mm = time.getMonth() + 1
    mm = mm < 10 ? '0' + mm : mm
    let dd = time.getDate()
    dd = dd < 10 ? '0' + dd : dd
    let hh = time.getHours()
    let mf = time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes()
    let ss = time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds()
    let timeStr = `${year}-${mm}-${dd} ${hh}:${mf}:${ss}`
    if (emptyStr) timeStr = timeStr.replace(/./g, '=')
    return timeStr
}

//执行command命令
const execCommand = (command) => {
    return new Promise((resolve, reject) => {
        if (command.indexOf("cd ") !== -1) {
            let dirPath = command.replace("cd ", "");//D:\WorkPlace\Git_Project
            try {
                process.chdir(dirPath);
                resolve({stdout: `进入目录【${process.cwd()}】成功！`})
            } catch (e) {
                console.log("cd command======error", e)
                reject(e)
            }
        } else if (command.indexOf("upload.sh ") !== -1) {
            let [p1, p2, p3] = command.split(" ").filter(item => item)
            console.log("upload.sh ====", p1, p2, p3)
            execFile(path.resolve(__dirname, 'upload.sh'), [p2, p3], (error, stdout, stderr) => {
                let result = {stdout, error, stderr}
                console.log("upload.sh =====", command, result)
                if (isTypeString(stdout) || isTypeString(stderr)) resolve(result)
                if (error) reject(error)
            })
        } else {
            try {
                exec(command, (error, stdout, stderr) => {
                    let result = {stdout, error, stderr}
                    console.log("execCommand=====", command, result)
                    if (isTypeString(stdout) || isTypeString(stderr)) resolve(result)
                    if (error) reject(error)
                });
            } catch (e) {
                console.log("execCommand=====", command, e)
                reject(e)
            }
        }
    })
}

//获取执行命令后的多条结果
const readResultLines = (result) => {
    if (result) return result.split("\n").filter(item => item.trim())
    else return []
}

//获取对象类型
const getValType = (val) => {
    return Object.prototype.toString.call(val).replace("[object ", "").replace("]", "")
}

//当前对象属性是否为字符串
const isTypeString = (val) => {
    return getValType(val) === "String"
}

//获取文件路径指定层级下的项目文件夹
const loadDir = (val, level = 2, filter = []) => {
    level = level - 1
    const files = fs.readdirSync(val).filter(item => !item.startsWith("."))
    if (level === 0) return files
    let dirObj = {}
    for (let i = 0; i < files.length; i++) {
        const fileItem = files[i]
        const fileItemDir = fs.lstatSync(`${val}/${fileItem}`)
        if (fileItemDir.isDirectory() && filter.indexOf(fileItem) === -1) {
            dirObj[fileItem] = loadDir(`${val}/${fileItem}`, level, filter)
        }
    }
    return dirObj
}

module.exports = {
    loadDir,
    getValType,
    execCommand,
    isTypeString,
    getCurrentTime,
    readResultLines,
}